import asyncio
from queue import Queue
from MyLib.TestToolApi import Debug
from MyLib.MyTranceChannel import Video_StoC_Main, Video_StoC_Sub, Audio_CTS_Channel, Audio_STC_Channel, SocketChannel


async def main_video_recv_watcher():
    debugQueue = Queue(1)
    debug = Debug(debugQueue, True, '视频流通道监听器(主)')
    video_StoC_main = Video_StoC_Main(recv_port_main=6100, sent_port_main=8104)
    video_StoC_main.openServer()
    await asyncio.sleep(0)
    debug.pushInfo("通道进程启动完成...", 'Debug')
    lastNums = 0
    countTime = 10
    allMs = 0
    no_connect = 0
    while True:
        if video_StoC_main.isOpened():
            mainNums, mainMs = video_StoC_main.getNums(), video_StoC_main.getMs()
            if mainNums > lastNums:
                if countTime > 0:
                    allMs += mainMs
                    countTime -= 1
                else:
                    countTime = 10
                    vergeMs = allMs / countTime
                    if vergeMs <= 30:
                        debug.pushInfo(f"10数据包内平均延时为：{vergeMs} ms, 状态良好!")
                    elif 30 < vergeMs <= 100:
                        debug.pushInfo(f"10数据包内平均延时为：{vergeMs} ms, 状态一般!", "Warning")
                    elif vergeMs > 100:
                        debug.pushInfo(f"10数据包内平均延时为：{vergeMs} ms, 状态不好!", "Error")
                    allMs = 0
                lastNums = mainNums
                no_connect = 0
            else:
                if mainNums != 0:
                    if no_connect < 5:
                        debug.pushInfo(f"警告! 无任何数据包接收!", "Error")
                        no_connect += 1
                    else:
                        debug.pushInfo(f"错误! 5s内无任何数据包接收, 重置连接!", 'Warning')
                        no_connect = 0
                        lastNums = 0
                        allMs = 0
                        video_StoC_main.closeServer()
                        video_StoC_main.join()
            await asyncio.sleep(1)
        else:
            debug.pushInfo(f"通信出现问题!重置连接中...", "Error")
            video_StoC_main.join()
            video_StoC_main = Video_StoC_Main(recv_port_main=6100, sent_port_main=8104)
            video_StoC_main.openServer()
            await asyncio.sleep(1)


async def sub_video_recv_watcher():
    debugQueue = Queue(1)
    debug = Debug(debugQueue, True, '视频流通道监听器(副)')
    video_StoC_sub = Video_StoC_Sub(recv_port_sub=6101, sent_port_sub=8105)
    video_StoC_sub.openServer()
    await asyncio.sleep(0)
    debug.pushInfo("通道进程启动完成...", 'Debug')
    lastNums = 0
    countTime = 10
    allMs = 0
    no_connect = 0
    while True:
        if video_StoC_sub.isOpened():
            mainNums, mainMs = video_StoC_sub.getNums(), video_StoC_sub.getMs()
            if mainNums > lastNums:
                if countTime > 0:
                    allMs += mainMs
                    countTime -= 1
                else:
                    countTime = 10
                    vergeMs = allMs / countTime
                    if vergeMs <= 30:
                        debug.pushInfo(f"10数据包内平均延时为：{vergeMs} ms, 状态良好!")
                    elif 30 < vergeMs <= 100:
                        debug.pushInfo(f"10数据包内平均延时为：{vergeMs} ms, 状态一般!", "Warning")
                    elif vergeMs > 100:
                        debug.pushInfo(f"10数据包内平均延时为：{vergeMs} ms, 状态不好!", "Error")
                    allMs = 0
                lastNums = mainNums
                no_connect = 0
            else:
                if mainNums != 0:
                    if no_connect < 5:
                        debug.pushInfo(f"警告! 无任何数据包接收!", "Error")
                        no_connect += 1
                    else:
                        debug.pushInfo(f"错误! 5s内无任何数据包接收, 重置连接!", 'Warning')
                        no_connect = 0
                        lastNums = 0
                        allMs = 0
                        video_StoC_sub.closeServer()
            await asyncio.sleep(1)
        else:
            debug.pushInfo(f"通信出现问题!重置连接中...", "Error")
            video_StoC_sub.join()
            video_StoC_sub = Video_StoC_Sub(recv_port_sub=6101, sent_port_sub=8104)
            video_StoC_sub.openServer()
            await asyncio.sleep(1)


async def audio_stc_channel_watcher():
    debugQueue = Queue(5)
    debug = Debug(debugQueue, True, '音频流通道监听器(STC)')
    audio_stc_channel = Audio_STC_Channel(recv_port_s=6511, sent_port_c=8212)
    audio_stc_channel.openServer()
    await asyncio.sleep(0)
    debug.pushInfo("通道进程启动完成...", 'Debug')
    lastNums = 0
    countTime = 10
    allMs = 0
    no_connect = 0
    while True:
        if audio_stc_channel.isOpened():
            mainNums, mainMs = audio_stc_channel.getNums(), audio_stc_channel.getMs()
            if mainNums > lastNums:
                if countTime > 0:
                    allMs += mainMs
                    countTime -= 1
                else:
                    countTime = 10
                    vergeMs = allMs / countTime
                    if vergeMs <= 30:
                        debug.pushInfo(f"10数据包内平均延时为：{vergeMs} ms, 状态良好!")
                    elif 30 < vergeMs <= 100:
                        debug.pushInfo(f"10数据包内平均延时为：{vergeMs} ms, 状态一般!", "Warning")
                    elif vergeMs > 100:
                        debug.pushInfo(f"10数据包内平均延时为：{vergeMs} ms, 状态不好!", "Error")
                    allMs = 0
                lastNums = mainNums
                no_connect = 0
            else:
                if mainNums != 0:
                    if no_connect < 5:
                        debug.pushInfo(f"警告! 无任何数据包接收!", "Error")
                        no_connect += 1
                    else:
                        debug.pushInfo(f"错误! 5s内无任何数据包接收, 重置连接!", 'Warning')
                        no_connect = 0
                        lastNums = 0
                        allMs = 0
                        audio_stc_channel.closeServer()
            await asyncio.sleep(1)
        else:
            debug.pushInfo(f"通信出现问题!重置连接中...", "Error")
            audio_stc_channel.join()
            audio_stc_channel = Audio_STC_Channel(recv_port_s=6511, sent_port_c=8212)
            audio_stc_channel.openServer()
            await asyncio.sleep(1)


async def audio_cts_channel_watcher():
    debugQueue = Queue(5)
    debug = Debug(debugQueue, True, '音频流通道监听器(CTS)')
    audio_cts_channel = Audio_CTS_Channel(recv_port_c=8211, sent_port_s=6512)
    audio_cts_channel.openServer()
    await asyncio.sleep(0)
    debug.pushInfo("通道进程启动完成...", 'Debug')
    lastNums = 0
    countTime = 10
    allMs = 0
    no_connect = 0
    while True:
        if audio_cts_channel.isOpened():
            mainNums, mainMs = audio_cts_channel.getNums(), audio_cts_channel.getMs()
            if mainNums > lastNums:
                if countTime > 0:
                    allMs += mainMs
                    countTime -= 1
                else:
                    countTime = 10
                    vergeMs = allMs / countTime
                    if vergeMs <= 30:
                        debug.pushInfo(f"10数据包内平均延时为：{vergeMs} ms, 状态良好!")
                    elif 30 < vergeMs <= 100:
                        debug.pushInfo(f"10数据包内平均延时为：{vergeMs} ms, 状态一般!", "Warning")
                    elif vergeMs > 100:
                        debug.pushInfo(f"10数据包内平均延时为：{vergeMs} ms, 状态不好!", "Error")
                    allMs = 0
                lastNums = mainNums
                no_connect = 0
            else:
                if mainNums != 0:
                    if no_connect < 5:
                        debug.pushInfo(f"警告! 无任何数据包接收!", "Error")
                        no_connect += 1
                    else:
                        debug.pushInfo(f"错误! 5s内无任何数据包接收, 重置连接!", 'Warning')
                        no_connect = 0
                        lastNums = 0
                        allMs = 0
                        audio_cts_channel.closeServer()
            await asyncio.sleep(1)
        else:
            debug.pushInfo(f"通信出现问题!重置连接中...", "Error")
            audio_cts_channel.join()
            audio_cts_channel = Audio_STC_Channel(recv_port_s=6511, sent_port_c=8212)
            audio_cts_channel.openServer()
            await asyncio.sleep(1)


async def socket_channel_watcher():
    debugQueue = Queue(5)
    debug = Debug(debugQueue, True, '控制|数据通道监听器(CTS)')
    socketChannel = SocketChannel(
        recv_port_c=8312, recv_port_s=6711,
        sent_port_c=8311, sent_port_s=6712
    )
    socketChannel.openServer()
    await asyncio.sleep(0)
    debug.pushInfo("通道进程启动完成...", 'Debug')
    while True:
        if socketChannel.isOpened():
            await asyncio.sleep(1)
        else:
            debug.pushInfo(f"通信出现问题!重置连接中...", "Error")
            socketChannel.closeServer()
            socketChannel.join()
            socketChannel = SocketChannel(
                recv_port_c=8312, recv_port_s=6711,
                sent_port_c=8311, sent_port_s=6712
            )
            socketChannel.openServer()
            await asyncio.sleep(1)

if __name__ == '__main__':
    loop = asyncio.new_event_loop()
    taskMainVideoRecv = loop.create_task(main_video_recv_watcher())
    taskSubVideoRecv = loop.create_task(sub_video_recv_watcher())
    taskAudioSTC = loop.create_task(audio_stc_channel_watcher())
    taskAudioCTS = loop.create_task(audio_cts_channel_watcher())
    taskSocketChannel = loop.create_task(socket_channel_watcher())

    async def main():
        await asyncio.gather(
            taskMainVideoRecv,
            taskSubVideoRecv,
            taskAudioSTC,
            taskAudioCTS,
            taskSocketChannel,
            loop=loop
        )

    loop.run_until_complete(main())
